﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PServiceBus.Core.Runtime {
    public class ShellHelper {
        private static void ExecuteFile(string filename, string arguments) {
            ProcessStartInfo info = new ProcessStartInfo(filename);
            info.Arguments = arguments;
            info.UseShellExecute = true;
            info.CreateNoWindow = true;
            info.ErrorDialog = false;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            var process = Process.Start(info);
            process.WaitForExit();
        }

        public static void NetShAddUrlAclAndSSL(int port, string thumbprint, string appid) {
            NetShAddUrlAcl(port);
            ExecuteFile("netsh.exe", String.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={2}",
                port, thumbprint, appid));
        }

        public static void NetShAddUrlAcl(int port) {
            ExecuteFile("netsh.exe", String.Format("http add urlacl url=https://+:{0}/ user={1}\\{2}",
               port, Environment.UserDomainName, Environment.UserName));
        }

        public static void NetShRemoveUrlAcl(int port) {
            ExecuteFile("netsh.exe", String.Format("http delete urlacl url=https://+:{0}/",
               port));
        }

        public static void NetShAddTCPFirewall(string name, string port) {
            name = name.Replace(" ", string.Empty);
            var ruleName = String.Concat(name, port);
            ExecuteFile("netsh.exe", String.Format("advfirewall firewall delete rule name=\"{0}\"", ruleName));
            ExecuteFile("netsh.exe", String.Format("advfirewall firewall add rule name=\"{0}\" dir=in action=allow protocol=TCP localport={1}", ruleName, port));
        }

        public static void NetShAddTCPFirewall(string name, int port) {
            NetShAddTCPFirewall(name, port.ToString());
        }
    }
}
